<?php

namespace App\Http\Middleware;

use App\Utils\ReqResLogger;
use Closure;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class UserRequestAndResponse
{
    protected string $sequence;
    protected string $code;

    const LOG_NAME = 'apiRequest';

    /**
     * 记录请求与响应数据
     *
     * UserRequestAndResponse constructor.
     * @param Request $request
     */
    public function __construct(Request $request)
    {
        $this->code     = $request->path();
        $this->sequence = str_pad(microtime(true), 15, 0);
    }

    /**
     * 处理主程序.
     *
     * @param Request $request
     * @param Closure $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        ReqResLogger::info("======================================" , [] , self::LOG_NAME);

        $this->request($request);

        $response = $next($request);
//    if ($response instanceof JsonResponse) {
//      $this->response($response);
//    }
        $this->time();
        ReqResLogger::info("======================================" , [] , self::LOG_NAME);
        return $response;
    }

    /**
     * 时间计算
     *
     */
    protected function time():void
    {
        $start = str_pad(LARAVEL_START, 15, 0);
        $end   = str_pad(microtime(true), 15, 0);
        $standard = config('develop.runtime-lower-limit');
        $time     = ($end - LARAVEL_START) * 1000;
        switch (true) {
            case $time > $standard:
                $mark = '超过[>]';
                $diff = $time - $standard;
                break;
            case $time === $standard:
                $mark = '持平[=]';
                $diff = 0;
                break;
            default:
                $mark = '低于[<]';
                $diff = $time - $standard;
        }
        $message = "请求序号[{$this->sequence}] 请求接口[{$this->code}] 开始时间[{$start}] 结束时间[{$end}] 运行时间[{$time}] {$mark}[{$standard}] {$diff}毫秒";

        ReqResLogger::info($message ,[], self::LOG_NAME);    }

    /**
     * 请求记录
     *
     * @param $request
     */
    protected function request($request):void
    {
        $input = $request->input();
        if (array_key_exists('data', $input)) {
            $input['data'] = json_decode($input['data'], true);
        }

        ReqResLogger::info("请求数据：" ,$input, self::LOG_NAME);    }

    /**
     * 响应记录
     *
     * @param JsonResponse $response
     */
    protected function response(JsonResponse $response):void
    {
        $output = json_decode($response->getContent(), true);
        if (json_last_error() === JSON_ERROR_NONE) {
            ReqResLogger::info("响应数据：" ,$output, self::LOG_NAME);                }
    }
}
